﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.IO;
using WoChu.CF.BaseFrame.Util;
using WoChu.CF.BaseFrame.Json;
using WoChu.CF.Base;

namespace WoChu.CF.BaseFrame.WebClient
{
    /// <summary>
    /// 
    /// </summary>
    public class ClientChannel: IDisposable
    {
        private string _BaseUri;

        /// <summary>
        /// 
        /// </summary>d
        public ClientChannel(string serviceName)
        {
            _BaseUri = string.Format(ClientChannelFactory.WEB_URL_ROOT_PATH, serviceName);
        }




        #region Get...
        /// <summary>
        /// Get调用
        /// </summary>
        /// <param name="uri"></param>
        /// <returns></returns>zzz
        public string Get(string methodUrl)
        {
            try
            {
                //Web访问对象
                string serviceUrl = string.Format("{0}/{1}", _BaseUri, methodUrl);
                HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(serviceUrl);
                myRequest.MaximumAutomaticRedirections = 10240;

                string returnJson = string.Empty;

                // 获得接口返回值
                using (HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse())
                {

                    using (StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8))
                    {
                        returnJson = HttpUtility.UrlDecode(reader.ReadToEnd());
                    }
                }
                return returnJson;
            }
            catch (System.Net.WebException ex)
            {
                var errResp = ex.Response as HttpWebResponse;

                if (errResp.StatusCode == HttpStatusCode.InternalServerError)
                {
                    using (var stream = errResp.GetResponseStream())
                    {
                        using (var sr = new StreamReader(stream))
                        {
                            throw new Exception(sr.ReadToEnd());
                        }
                    }
                }

                throw ex;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        ///  Get调用
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="methodUrl"></param>
        /// <returns></returns>
        public T Get<T>(string methodUrl)
        {
            //MB.CF.BaseFrame.Util.TraceEx.Write("Get[" + methodUrl + "] begin " + DateTime.Now.ToLongTimeString());

            string re = Get(methodUrl);
            if(string.IsNullOrEmpty(re)) return default(T);
            //MB.CF.BaseFrame.Util.TraceEx.Write("Get[" + methodUrl + "] end " + DateTime.Now.ToLongTimeString());

            return Converter.Deserialize<T>(re);
        }
        #endregion ...

        #region post ...
        /// <summary>
        /// Post调用
        /// </summary>
        /// <param name="data"></param>
        /// <param name="uri"></param>
        /// <returns></returns>
        public string Post(string jsonData, string methodUrl)
        {
            try
            {
                //Web访问对象
                string serviceUrl = string.Format("{0}/{1}", _BaseUri, methodUrl);
                HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(serviceUrl);
                //myRequest.MaximumResponseHeadersLength = 10240;
                myRequest.MaximumAutomaticRedirections = 10240;
        

                //转成网络流
                byte[] buf = UnicodeEncoding.UTF8.GetBytes(jsonData);

                //设置
                myRequest.Method = "POST";
                myRequest.ContentLength = buf.Length;
                myRequest.ContentType = "application/json; charset=utf-8";//"application/x-www-form-urlencoded";//"text/html";

                // 发送请求
                using (Stream newStream = myRequest.GetRequestStream())
                {
                    newStream.Write(buf, 0, buf.Length);
                }
                string returnJson = string.Empty;
                // 获得接口返回值
                using (HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse())
                {
                    using (StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8))
                    {
                        returnJson = HttpUtility.HtmlDecode(reader.ReadToEnd());
                    }
                }
                return returnJson;
            }
            catch (System.Net.WebException ex)
            {
                var errResp = ex.Response as HttpWebResponse;
                if (errResp.StatusCode == HttpStatusCode.InternalServerError)
                {
                    using (var stream = errResp.GetResponseStream())
                    {
                        using (var sr = new StreamReader(stream))
                        {
                            throw new Exception(sr.ReadToEnd());
                        }
                    }
                }

                throw ex;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// Post调用
        /// </summary>
        /// <typeparam name="TInput"></typeparam>
        /// <typeparam name="TResult"></typeparam>
        /// <param name="data"></param>
        /// <param name="methodUrl"></param>
        /// <returns></returns>
        public TResult Post<TInput, TResult>(TInput data, string methodUrl)
        {
            try
            {
                string jsonData = Converter.Serialize(data);
                string re = Post(jsonData, methodUrl);
                return Converter.Deserialize<TResult>(re);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion ...

        #region IDisposable 成员

        #region IDisposable...
        private bool disposed = false;

        /// <summary>
        /// Dispose
        /// </summary>
        public void Dispose()
        {
            Dispose(true);
            //
            GC.SuppressFinalize(this);
        }
        private void Dispose(bool disposing)
        {
            if (!this.disposed)
            {
                if (disposing)
                {


                }
                disposed = true;
            }
        }

        ~ClientChannel()
        {

            Dispose(false);
        }

        #endregion IDisposable...

        #endregion
    }
}
